package com.neusoft.demo.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.neusoft.demo.config.ElasticsearchConfig;
import com.neusoft.demo.dao.UserDao;
import com.neusoft.demo.entity.User;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhouQF
 * @description
 * @date 2019/9/16
 */

@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    private void setRestHighLevelClient(){
        if(restHighLevelClient == null){
            ElasticsearchConfig elasticsearchConfig = new ElasticsearchConfig();
            restHighLevelClient = elasticsearchConfig.restHighLevelClient();
        }
    }

    public static void main(String[] args) throws IOException {
        UserService userService = new UserService();
        userService.setRestHighLevelClient();
        //userService.updateOrAdd();
        userService.updateOrAdd();
    }

    /**
     * 新建索引
     */
    public void createIndex() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("customer2");
        request.settings(Settings.builder()
                .put("index.number_of_shards", 3)
                .put("index.number_of_replicas", 2)
        );
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse.index());
        restHighLevelClient.close();
    }

    /**
     * 新增或者修改
     * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.3/java-rest-high-document-index.html
     * http://localhost:9200/customer2/_doc/1?pretty
     * @throws IOException
     */
    public void updateOrAdd() throws IOException {
        IndexRequest request = new IndexRequest("customer2");
        request.id("1");
        String jsonString = "{" +
                "\"user\":\"kimchy12\"," +
                "\"postDate\":\"2013-01-30\"," +
                "\"message\":\"trying out Elasticsearch\"" +
                "}";
        request.source(jsonString, XContentType.JSON);
        IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        System.out.println(indexResponse.status());
        restHighLevelClient.close();
    }

    /**
     * 查询索引里的数据
     * @throws IOException
     */
    public void queryIndex() throws IOException {
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("customer");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

//        searchSourceBuilder.query(QueryBuilders.termQuery("title.keyword", "python分布式爬虫开发"))
//                .from(0).size(100);

        searchSourceBuilder.query(QueryBuilders.matchAllQuery())
                .from(0).size(100);

        searchRequest.source(searchSourceBuilder);

        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }

        restHighLevelClient.close();
    }

    /**
     * 删除索引
     * @throws IOException
     */
    public void deleteIndex() throws IOException {
        DeleteIndexRequest deleteRequest = new DeleteIndexRequest("customer2");

        AcknowledgedResponse deleteIndexResponse = restHighLevelClient.indices().delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(deleteIndexResponse.isAcknowledged());

        restHighLevelClient.close();
    }

    public List<User> demo(User user){
        PageHelper.startPage(1, 10);
        Page list = (Page)userDao.queryInfo(user);
        return list;
    }

    public int demo1(User user){
       return  userDao.updateInfo(user);
    }














    public Map<String, Object> userList(HttpServletRequest request, User user){
        PageHelper.startPage(request);
        Map<String, Object> res = new HashMap<>();
        Page<User> page = (Page) userDao.userList(user);
        res.put("msg", "调用成功");
        res.put("code", 0);
        res.put("count", page.getTotal());
        res.put("data", page.getResult());
        return res;
    }

    public String saveUser(User user){
        if(StringUtils.isEmpty(user.getId())){
            // 1. 判断userName不等于空
            if(StringUtils.isEmpty(user.getUserName())){
                return "error";
            }
            // 2.判断userName不重复
            List<User> list = userDao.queryOneUser(user);

            if(list.size() > 0){
                return "error";
            }

            int res = userDao.saveUser(user);
        }else {
            int res = userDao.updateUser(user);
        }
        return "success";
    }
}
